﻿using System;
using System.Data;
using System.Text;
using System.Configuration;
using System.Web;
using System.Reflection;
using System.Text.RegularExpressions;
using System.Web.Configuration;

namespace SyCODE.Component
{
    /// <summary>
    /// 公用小功能
    /// </summary>
    public class Function
    {
        static void ClientMethod(string message, string active)
        {
            HttpResponse response = HttpContext.Current.Response;
            response.Expires = -1;
            response.ContentType = "text/html; charset=" + HttpContext.Current.Request.ContentEncoding.WebName;
            response.AppendHeader("Active", active);
            response.Clear();
            response.Write(message);
        }
        /// <summary>
        /// 获取用户真实IP地址
        /// </summary>
        /// <returns></returns>
        public static string GetUserIp()
        {
            string ip = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
            if (ip == null || ip.Length == 0 || ip.ToLower().IndexOf("unknown") > -1)
            {
                ip = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
            }
            else
            {
                if (ip.IndexOf(',') > -1)
                {
                    ip = ip.Substring(0, ip.IndexOf(','));
                }
                if (ip.IndexOf(';') > -1)
                {
                    ip = ip.Substring(0, ip.IndexOf(';'));
                }
            }

            Regex regex = new Regex("[^0-9.]");
            if (ip == null || ip.Length == 0 || regex.IsMatch(ip))
            {
                ip = HttpContext.Current.Request.UserHostAddress;
                if (ip == null || ip.Length == 0 || regex.IsMatch(ip))
                {
                    ip = "0.0.0.0";
                }
            }
            return ip;
        }

        /// <summary>
        /// 向WEB浏览器传输信息并设置执行动作为alert
        /// </summary>
        /// <param name="message">要发送的消息内容</param>
        public static void ClientAlert(string message)
        {
            ClientMethod(message, "alert");
        }

        /// <summary>
        /// 向WEB浏览器传输信息并设置执行动作为eval
        /// </summary>
        /// <param name="message">要发送的消息内容</param>
        public static void ClientScript(string message)
        {
            ClientMethod(message, "eval");
        }

        /// <summary>
        /// 生成指定长度的随机ASCII字符串
        /// </summary>
        /// <param name="len">要生成的随机字符串的长度</param>
        /// <returns></returns>
        public static string RandomString(int len)
        {
            int num;
            char chr;
            string str = String.Empty;

            System.Random random = new Random();

            for (int i = 0; i < len; i++)
            {
                num = random.Next();

                switch (random.Next(3))
                {
                    case 0:
                        chr = (char)(num % 10 + 48);
                        break;
                    case 1:
                        chr = (char)(num % 26 + 97);
                        break;
                    default:
                        chr = (char)(num % 26 + 65);
                        break;
                }

                str += chr.ToString();
            }

            return str;
        }

        /// <summary>
        /// 对字符串进行兼容javascript脚本语言的ecsape编码
        /// </summary>
        /// <param name="s"></param>
        /// <returns></returns>
        public static string Escape(string s)
        {
            StringBuilder sb = new StringBuilder();
            byte[] ba = System.Text.Encoding.Unicode.GetBytes(s);
            for (int i = 0; i < ba.Length; i += 2)
            {
                sb.Append("%u");
                sb.Append(ba[i + 1].ToString("X2"));
                sb.Append(ba[i].ToString("X2"));
            }
            return sb.ToString();
        }

        /// <summary>
        /// 字符串裁剪
        /// </summary>
        /// <param name="str"></param>
        /// <param name="length"></param>
        /// <returns></returns>
        public static string StringCut(string str, int length)
        {
            if (str.Length > length)
            {
                str = str.Substring(0, length - 3) + "...";
            }
            return str;
        }

        /// <summary>
        /// 获得当前系统的Response编码
        /// </summary>
        /// <returns></returns>
        public static Encoding GetEncoding()
        {
            Encoding encoding = Encoding.UTF8;

            object config = WebConfigurationManager.GetWebApplicationSection("system.web/globalization");
            Type type1 = config.GetType();

            if (type1 != null)
            {
                PropertyInfo pinfo = type1.GetProperty("responseEncoding", BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase);
                if (pinfo != null)
                {
                    encoding = (Encoding)pinfo.GetValue(config, null);
                }
                else
                {
                    FieldInfo finfo = type1.GetField("responseEncoding", BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase);
                    if (finfo != null)
                    {
                        encoding = (Encoding)finfo.GetValue(config);
                    }
                }
            }

            return encoding;
        }

        private static Regex utf8UrlCode = new Regex(@"%e[0-9a-f]%[89ab][0-9a-f]%[89ab][0-9a-f]", RegexOptions.IgnoreCase);
        public static string UrlDecode(string url)
        {
            string gbk = utf8UrlCode.Replace(url, delegate(Match m)
                    {
                        return HttpUtility.UrlDecode(m.Value, Encoding.UTF8);
                    });

            return HttpUtility.UrlDecode(gbk, Encoding.Default);
        }

        /// <summary>
        /// 危险标签清理
        /// </summary>
        /// <param name="html"></param>
        /// <returns></returns>
        public static string DangerTagsFilter(string html)
        {
            html = Regex.Replace(html, @"<[/]?\s*i\s*f\s*r\s*a\s*m\s*e[^>]*>", "", RegexOptions.IgnoreCase);
            html = Regex.Replace(html, @"<[/]?\s*f\s*r\s*a\s*m\s*e\s*s\s*e\s*t[^>]*>", "", RegexOptions.IgnoreCase);

            html = Regex.Replace(html, @"<(?![/]?script)([^>]*)>",
                delegate(Match m)
                {
                    string tag = m.Value;
                    tag = Regex.Replace(tag, @"[\s-]*s\s*c\s*r\s*i\s*p\s*t", "-script", RegexOptions.IgnoreCase);
                    tag = Regex.Replace(tag, @"[\s-]*e\s*x\s*p\s*r\s*e\s*s\s*s\s*i\s*o\s*n", "-expression", RegexOptions.IgnoreCase);
                    tag = Regex.Replace(tag, @"([/\s]+)(on[^=]+=)", " _$2", RegexOptions.IgnoreCase);
                    return tag.Replace("&", "&amp;");
                }, RegexOptions.IgnoreCase);

            html = Regex.Replace(html, @"(<script[^>]*[\s\/]+)(defer)(.*>)", "$1_defer$3", RegexOptions.IgnoreCase);
            return Regex.Replace(html, @"(<[/]?)(style[^>]*>)", "$1T:$2", RegexOptions.IgnoreCase); ;
        }
    }
}